package cn.it.executor;

import cn.it.pojo.Configuration;
import cn.it.pojo.MappedStatement;
import cn.it.utils.GenericTokenParser;
import cn.it.utils.ParameterMapping;
import cn.it.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Exector {

    @Override
    public List<Object> query(Configuration configuration, MappedStatement mappedStatement, Object param) throws Exception {

        PreparedStatement preparedStatement = init(configuration, mappedStatement, param);

        // 执行
        ResultSet resultSet = preparedStatement.executeQuery();

        // 封装结果集
        List<Object> resultList = new ArrayList<>();
        Class<?> resultType = getTypeClass(mappedStatement.getResultType());
        while (resultSet.next()) {
            Object result = resultType.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor descriptor = new PropertyDescriptor(columnName, resultType);
                descriptor.getWriteMethod().invoke(result, value);
            }
            resultList.add(result);
        }

        return resultList;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object param) throws Exception {
        PreparedStatement preparedStatement = init(configuration, mappedStatement, param);
        return preparedStatement.executeUpdate();
    }

    private PreparedStatement init(Configuration configuration, MappedStatement mappedStatement, Object param) throws Exception {
        // 获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();

        // 解析sql和参数
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());

        // 预处理
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        //设置参数
        if (param != null) {
            if (param instanceof Integer){
                // Integer
                preparedStatement.setObject(1,param);
            }else {
                // 对象
                Class<?> paramterType = getTypeClass(mappedStatement.getParamterType());
                for (int i = 0; i < boundSql.getParameterNames().size(); i++) {
                    Field field = paramterType.getDeclaredField(boundSql.getParameterNames().get(i).getContent());
                    field.setAccessible(true);
                    // field.get(param) 获取对象在该属性上的值
                    preparedStatement.setObject(i + 1, field.get(param));
                }
            }
        }

        return preparedStatement;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterNames = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parseSql, parameterNames);
    }

    private Class<?> getTypeClass(String typeName) throws ClassNotFoundException {
        if (typeName != null) {
            Class<?> aClass = Class.forName(typeName);
            return aClass;
        }
        return null;
    }
}
